<template>
  <el-config-provider :locale="currentLocale">
    <router-view />
  </el-config-provider>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTransferStore } from '@/stores/transfer'
import { useUserStore } from '@/stores/user'
import { useThemeStore } from '@/stores/theme'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/dist/locale/en.mjs'
import { ElConfigProvider } from 'element-plus'

// 应用根组件
const router = useRouter()
const transferStore = useTransferStore()
const userStore = useUserStore()
const themeStore = useThemeStore()

const currentLocale = computed(() => {
  return themeStore.language === 'zh-CN' ? zhCn : en
})

// 应用挂载时初始化全局连接
onMounted(async () => {
  // 检查用户是否已登录
  if (userStore.isLoggedIn) {
    try {
      // 从用户状态管理中获取用户ID
      const userId = userStore.getCurrentUserId()
      await transferStore.initSocket(userId)
      console.log('✅ 传输系统已启动')

    } catch (error) {
      console.error('❌ 全局服务初始化失败:', error)
      // 静默处理错误，避免影响应用启动
    }
  }
  themeStore.initTheme()
})

// 应用卸载时清理连接
onUnmounted(() => {
  transferStore.disconnectSocket()
})

// 监听路由变化，处理登录状态变化
router.afterEach(async (to, from) => {
  // 如果从登录页面跳转到其他页面，且已登录，初始化连接
  if (from.path === '/auth/login' && userStore.isLoggedIn && !transferStore.isConnected) {
    const userId = userStore.getCurrentUserId()
    await transferStore.initSocket(userId)
  }

  // 如果跳转到登录页面，断开连接
  if (to.path === '/auth/login' && transferStore.isConnected) {
    transferStore.disconnectSocket()
  }
})
</script>

<style lang="scss">
#app {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
